<!-- 首页 -->
<template>
	<view class="container">
		<view class="m-t26 flex align-end m-b20">
			<text class="text-gray f-s12 m-r10">当前位置</text>
			<image src="/static/images/login/location.png" class="width-16 height-16 m-r4 self-center" mode="widthFix">
			</image>
			<text class="f-s15 text-bold">{{address}}</text>
		</view>
		<view class="m-b20 line"></view>
		<van-picker :columns="columns" @change="handlePickerChange" ref="picker">
			<template slot="columns-top">
				<view class="flex text-center text-bold f-s15">
					<text class="flex-sub">省份</text>
					<text class="flex-sub">城市</text>
					<text class="flex-sub">区县</text>
				</view>
			</template>
		</van-picker>
		<Toast></Toast>
	</view>
</template>

<script>
	import areaList from '@/common/database_area.js';
	import permision from "@/common/permission.js"
	export default {
		name: "",
		props: {
			value: {
				type: [Number, String],
				default: undefined,
			},
			isConfirm:{
				type:Boolean
			}
		},
		data() {
			return {
				address: '正在定位..',
				tree: [], // 树状结构数据
				columns: [{
						values: [], // 省份列表
						defaultIndex: 0,
					},
					{
						values: [], // 城市列表
						defaultIndex: 0,
					},
					{
						values: [], // 区县列表
						defaultIndex: 0,
					},
				]
			}
		},
		watch: {
			isConfirm:{
				immediate: true,
				handler(val){
					if(val){
						let values = this.$refs['picker'].getValues()
						this.$emit('input', values.map(item => item.text).join("/"))
						
					}
				}
			},
			value: {
				immediate: true,
				handler(val) {
					this.tree = this.buildTree(areaList.province_list, areaList.city_list, areaList.county_list)
					this.initColumns()
					if (val) {
						let list = val.split('/')
						this.setDefaultSelectionByLabel(list[0], list[1], list[2])
					}
				}
			}
		},
		created() {
			this.checkPermission()

		},
		methods: {
			initColumns() {
				// 初始化省份列
				this.columns[0].values = this.tree.map(p => ({
					text: p.label,
					value: p.value
				}));

				// 初始化默认选中的省、市、区
				const defaultProvince = this.tree[0];
				if (defaultProvince?.children?.length) {
					this.columns[1].values = defaultProvince.children.map(c => ({
						text: c.label,
						value: c.value
					}));
					const defaultCity = defaultProvince.children[0];
					if (defaultCity?.children?.length) {
						this.columns[2].values = defaultCity.children.map(a => ({
							text: a.label,
							value: a.value
						}));
					}
				}
			},
			// 根据 label 设置默认选中的省市区
			setDefaultSelectionByLabel(provinceLabel, cityLabel, countyLabel) {
				// 设置省份默认选中
				const provinceIndex = this.tree.findIndex(p => p.label === provinceLabel);
				if (provinceIndex !== -1) {
					// this.columns[0].defaultIndex = provinceIndex;
					this.$set(this.columns[0], 'defaultIndex', provinceIndex)
					// 设置城市默认选中
					const province = this.tree[provinceIndex];
					const cityIndex = province.children.findIndex(c => c.label === cityLabel);
					if (cityIndex !== -1) {
						this.columns[1].values = province.children.map(c => ({
							text: c.label,
							value: c.value
						}));
						// this.columns[1].defaultIndex = cityIndex;
						this.$set(this.columns[1], 'defaultIndex', cityIndex)
						// 设置区县默认选中
						const city = province.children[cityIndex];
						const countyIndex = city.children.findIndex(a => a.label === countyLabel);
						if (countyIndex !== -1) {
							this.columns[2].values = city.children.map(a => ({
								text: a.label,
								value: a.value
							}));
							// this.columns[2].defaultIndex = countyIndex;
							this.$set(this.columns[2], 'defaultIndex', countyIndex)
						}
					}
				}
			},
			// 当 picker 变化时触发
			handlePickerChange(event) {
				const {
					picker,
					value: values,
					index
				} = event.detail;
				if (index == 0) {
					const provinceValue = values[0]?.value;
					const province = this.tree.find(p => p.value === provinceValue);

					if (!province?.children?.length) {
						picker.setColumnValues(1, []);
						picker.setColumnValues(2, []);
						return;
					}

					// 更新城市列
					const cities = province.children.map(c => ({
						text: c.label,
						value: c.value
					}));
					picker.setColumnValues(1, cities);

					// 重置城市列选中项为第一个，并手动触发城市列的 change 事件
					this.$nextTick(() => {
						picker.setColumnIndex(1, 0); // 重置选中项
						const newValues = picker.getValues(); // 获取最新的 values
						this.handlePickerChange({
							detail: {
								picker,
								value: newValues,
								index: 1, // 模拟城市列变化
							},
						});
					});
				}

				// 城市变化时
				if (index == 1) {
					const provinceValue = values[0]?.value;
					const cityValue = values[1]?.value;

					const province = this.tree.find(p => p.value === provinceValue);
					if (!province?.children?.length) {
						picker.setColumnValues(2, []);
						return;
					}

					const city = province.children.find(c => c.value === cityValue);
					if (!city?.children?.length) {
						picker.setColumnValues(2, []);
						return;
					}

					// 更新区县列
					const counties = city.children.map(a => ({
						text: a.label,
						value: a.value
					}));
					picker.setColumnValues(2, counties);
					picker.setColumnIndex(2, 0);
				}
			},
			async checkPermission() {
				let status = permision.isIOS ? await permision.requestIOS('location') :
					await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
				if (status === null || status === 1) {
					status = 1;
					this.getLocaction()
				} else if (status === 2) {
					// 定位服务未启用
					this.address = '定位服务未开启'
					this.$toast("定位服务未开启")
				} else {
					this.address = '定位权限未开启'
					uni.showModal({
						title: "提示",
						content: '定位权限未开启，请前往设置打开授权',
						confirmText: '前往设置',
						success(res) {
							if (res.confirm) {
								uni.openAppAuthorizeSetting()
							}
						}
					})
				}

				return status;
			},
			buildTree(provinceList, cityList, countyList) {
				const tree = [];

				// 1. 处理省份
				for (const provinceCode in provinceList) {
					const provinceNode = {
						value: provinceCode,
						label: provinceList[provinceCode],
						children: [],
					};
					tree.push(provinceNode);
				}

				// 2. 处理城市
				for (const cityCode in cityList) {
					const provinceCode = cityCode.substring(0, 2) + '0000'; // 提取省份代码
					const provinceNode = tree.find(node => node.value === provinceCode);

					if (provinceNode) {
						const cityNode = {
							value: cityCode,
							label: cityList[cityCode],
							children: [],
						};
						provinceNode.children.push(cityNode);
					}
				}

				// 3. 处理区县
				for (const countyCode in countyList) {
					const cityCode = countyCode.substring(0, 4) + '00'; // 提取城市代码
					const provinceNode = tree.find(node => node.value === cityCode.substring(0, 2) + '0000');

					if (provinceNode) {
						const cityNode = provinceNode.children.find(node => node.value === cityCode);
						if (cityNode) {
							const countyNode = {
								value: countyCode,
								label: countyList[countyCode],
							};
							cityNode.children.push(countyNode);
						}
					}
				}

				return tree;
			},
			getLocaction() {
				// 获取当前位置
				uni.getLocation({
					geocode: true,
					type: 'gcj02',
					success: (res) => {
						let {
							address,
							latitude,
							longitude
						} = res;
						let {
							province,
							city,
							district,
							street,
							poiName
						} = address;
						this.address = `${province}${city}${district}`
						// 无选中值则赋值当前位置
						if (!this.value) {
							// this.handleMatchingCode(district, city)
							this.$emit('input', `${province}/${city}/${district}`)
						}
					},
					fail: (err) => {
						console.log('err: ', err)
						this.address = '定位失败'
					}
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.container {
		::v-deep .van-picker__toolbar {
			display: none;
		}

	}
</style>